package com.mdnote.structure.sparse_array;

import java.util.Arrays;

/**
 * @author Rhythm-2019
 * @date 2020/8/9
 * @description 稀树数组
 */
public class SparseArray {

    private int[][] sparseArray;

    public SparseArray(int[][] sourseArray) {
        int height = sourseArray.length;
        int width = sourseArray[0].length;
        int count = 0;
        for (int[] row : sourseArray) {
            for (int i : row) {
                if (i != 0) {
                    count++;
                }
            }
        }
        this.sparseArray = new int[count + 1][3];
        this.sparseArray[0][0] = height;
        this.sparseArray[0][1] = width;
        this.sparseArray[0][2] = count;

        count = 1;
        for (int i = 0; i < sourseArray.length; i++) {
            for (int j = 0; j < sourseArray[i].length; j++) {
                if (sourseArray[i][j] != 0) {
                    this.sparseArray[count][0] = i;
                    this.sparseArray[count][1] = j;
                    this.sparseArray[count][2] = sourseArray[i][j];
                    count++;
                }
            }
        }
    }

    public int[][] toSourseArray() {
        int height = this.sparseArray[0][0];
        int width = this.sparseArray[0][1];

        int[][] sourseArray = new int[height][width];
        for (int i = 1; i < this.sparseArray.length; i++) {
            int[] row = this.sparseArray[i];
            sourseArray[row[0]][row[1]] = row[2];
        }
        return sourseArray;
    }
    // 输出数组
    public void print() {
        for (int[] row : this.sparseArray) {
            System.out.println(Arrays.toString(row));
        }
    }
    public static void main(String[] args) {
        int[][] sourse = new int[5][5];
        sourse[0][3] = 1;
        sourse[1][3] = 2;

        for (int[] row : sourse) {
            System.out.println(Arrays.toString(row));
        }

        System.out.println("--------------------------");

        SparseArray sparseArray = new SparseArray(sourse);
        sparseArray.print();

        System.out.println("--------------------------");
        int[][] sourseArray = sparseArray.toSourseArray();
        for (int[] row : sourseArray) {
            System.out.println(Arrays.toString(row));
        }
    }


}
